from lxml import etree
import requests
import json
import pymysql

def get_one_stock(url, stockcode):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        '(KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
    }
    url = url + stockcode + '.html'
    res = requests.get(url, headers=headers)
    if res.status_code == 200 and res.text.find(stockcode) != -1:
        print(url)
        # print(res.text.find(stockcode))
        return res.text
    print(stockcode + ' is not found')
    return None

def parse_one_stock(text):
    html = etree.HTML(text)
    lszjlx_data_free = html.xpath('//div[@id="lszjlx_data_free"]/text()')
    ss = json.loads(lszjlx_data_free[0]) # 转换lszjlx_data_free的类型为由dict组成的list
    print(type(ss[1]))

def save_html(name, text):
    with open(name, 'w', encoding='utf-8') as f:
        f.write(text)

def save_db():
    db = pymysql.connect(host='localhost',user='root',password='257911',port=3306)
    cursor = db.cursor()
    create = 'CREATE DATABASE stock DEFAULT CHARACTER SET utf8'
    cursor.execute(create)

# url2 = 'http://stockpage.10jqka.com.cn/'
url = 'http://data.eastmoney.com/zjlx/'
text = get_one_stock(url, '000001')
print(text)
# parse_one_stock(text)
# save_html('tt.txt', lszjlx_data_free)
